package itsm.isperp.workflow.web.controller;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.framework.web.utils.DataRequestUtils;
import itsm.isperp.module.service.bpm.act.BpmActService;
import itsm.isperp.workflow.dto.ProcessDefinitionDTO;
import itsm.isperp.workflow.service.BpmProcessDefinitaionService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;

import org.activiti.engine.repository.ProcessDefinition;
import org.apache.ibatis.annotations.Param;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * 
 * 
 * @author lizx
 * @date 2013-4-24
 */
@Controller
@RequestMapping("workflow/processDefinition")
@ResponseBody
public class ProcessDefinitionController {

	@Autowired
	BpmActService bpmActService;

	@Autowired
	BpmProcessDefinitaionService bpmProcessDefinitaionService;

	/**
	 * 流程定义列表
	 */
	@RequestMapping("list")
	@ResponseBody
	public DataResponse<ProcessDefinition> list(JqGridRequest request,
			HttpServletRequest req) {

		DataResponse<ProcessDefinition> response = DataRequestUtils
				.buildFormQuery(request, bpmProcessDefinitaionService
						.createProcessDefinitionQuery().active()
						.orderByProcessDefinitionVersion().desc());

		List<ProcessDefinitionDTO> list = new ArrayList<ProcessDefinitionDTO>();

		for (ProcessDefinition pd : response) {
			list.add(new ProcessDefinitionDTO(pd));
		}

		response.getContent().clear();
		response.getContent().addAll(list);
		return response;

	}

	/**
	 * 查看流程图
	 * 
	 * @param defId
	 *            流程定义的id
	 * @param response
	 *            http响应
	 * @throws Exception
	 */
	@RequestMapping(value = "processImage/{defId}")
	public void processImage(@PathVariable("defId") String defId,
			HttpServletResponse response) throws Exception {
		response.getOutputStream().write(
				this.bpmProcessDefinitaionService.processImage(defId));
	}

	@RequestMapping(value = "traceDefView")
	@ResponseBody
	public ModelAndView traceDefView(String processKey)
			throws IOException, DocumentException {

		ModelAndView mv = new ModelAndView(
				"workflow/processDefinition/traceDef");

		ProcessDefinition pDef = this.bpmProcessDefinitaionService
				.getProcessDefinitionByKey(processKey);

		mv.addObject("processDefId", pDef.getId());

		return mv;

	}

	/**
	 * 导出流程部署的xml文件
	 * 
	 * @throws IOException
	 * 
	 */
	@RequestMapping(value = "exportXml/{deploymentId}")
	public void exportXml(@PathVariable("deploymentId") String deploymentId,
			HttpServletResponse response) throws IOException {

		response.getWriter().write(
				bpmActService.getProcessDefinitionXmlByDeployId(deploymentId)
						.toString());
	}

	@RequestMapping(value = "saveCondition")
	@ResponseBody
	public ResultMessage saveCondition(String defId, String deployId,
			String nodeId, String tasks, String conditions) throws IOException,
			DocumentException {

		String[] aryTasks = tasks.split(",");
		String[] aryCondition = conditions.split(",");
		Map<String, String> map = new HashMap<String, String>();

		for (int i = 0; i < aryTasks.length; i++) {
			map.put(aryTasks[i], aryCondition[i]);
		}
		this.bpmProcessDefinitaionService.saveCondition(defId, deployId,
				nodeId, map);
		return ResultMessage.success();
	}

	@RequestMapping(value = "deployEdit")
	public ModelAndView deployEdit(String filePath) {

		return new ModelAndView("workflow/processDefinition/deployEdit");
	}
	
	@RequestMapping(value = "deployNewProcessEdit")
	public ModelAndView deployNewProcessEdit() {
		return new ModelAndView("workflow/processDefinition/deployNewProcessEdit");
	}

	@RequestMapping(value = "deploy")
	public ResultMessage deploy(String filePath, String processName)
			throws IOException, UnsupportedEncodingException,
			XMLStreamException {

		this.bpmProcessDefinitaionService.deploy(processName,
				ContextHolder.getApplicationPath() + "/" + filePath);

		return ResultMessage.success();
	}

	/**
	 * 新增流程
	 * @param processName
	 * @param processKey
	 * @return
	 * @throws JsonProcessingException
	 * @throws XMLStreamException
	 * @throws IOException
	 */
	@RequestMapping(value = "deployNewProcess", method= RequestMethod.POST)
	public ResultMessage deployNewProcess(@RequestParam("processName") String processName, @RequestParam("processKey")String processKey)
			throws JsonProcessingException, XMLStreamException, IOException {
		this.bpmProcessDefinitaionService.deployNewProcess(processName, processKey);
		return ResultMessage.success();
	}
}